<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小账单物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82882996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\approval;

use think\App;
use app\controller\property\Base;
use app\validate\work\WorkExpendApplyValidate;
use app\validate\approval\ApprovalReceivesValidate;
use app\common\repositories\approval\ApprovalLogRepository;
use app\common\repositories\work\WorkExpendApplyRepository;
use app\common\repositories\approval\ApprovalFlowRepository;
use app\common\repositories\approval\ApprovalConfigRepository;
use app\common\repositories\approval\ApprovalReceivesRepository;

class ApprovalReceives extends Base
{

    protected $repository;

    public function __construct(App $app, ApprovalReceivesRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyPropertyBillDayAdd'),
            'editAuth' => property_auth('propertyApprovalReceivesSubmitEdit'),
            'delAuth' => property_auth('propertyApprovalReceivesSubmitDel'),
            'detailAuth' => property_auth('propertyApprovalReceivesSubmitDetail'),
            'readAuth' => property_auth('propertyApprovalReceivesApprovalReadInfo'),## 阅读
            'approvalAuth' => property_auth('propertyApprovalReceivesApprovalSubmitData'), ## 审批
        ]);
    }

    protected function commonParams()
    {
        /** @var ApprovalConfigRepository $configRepository */
        $configRepository = app()->make(ApprovalConfigRepository::class);
        $flowTypeData = $configRepository::FLOW_TYPE_B;
        $this->assign([
            'flowTypeData' => $flowTypeData
        ]);
    }

    /**
     *  待我审批的
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-05-21 21:18
     */
    public function stayMyApproval()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'flow_type' => '',
                'keywords' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $where['is_type'] = [2, 3];
            $where['verify_type'] = 1;
            $where['present_uid'] = $this->request->userId;
            $data = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        $this->commonParams();
        return $this->fetch('approval/receives/stayMyApproval');
    }

    /**
     * 抄送至我的
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-05-21 21:19
     */
    public function copyItToMe()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'flow_type' => '',
                'day_time' => '',
                'keywords' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $where['is_type'] = [2, 3];
            $where['verify_type'] = 3;
            $where['present_uid'] = $this->request->userId;
            $data = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        $this->commonParams();
        return $this->fetch('approval/receives/copyItToMe');
    }

    /**
     * 阅读
     * @param ApprovalReceivesRepository $repository
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-05-24 07:47
     */
    public function readApproval()
    {
        $receivesId = (int)$this->request->param('receives_id');
        if ($receivesId <= 0) {
            return $this->error('参数错误');
        }
        $receivesInfo = $this->repository->get($receivesId);
        if (!$receivesInfo) {
            return $this->error('信息不存在');
        }
        if ($receivesInfo['present_uid'] != $this->request->userId) {
            return $this->error('非法操作');
        }
        ## 调整阅读
        if ($receivesInfo['is_check'] == 1) {
            $receivesInfo->is_check = 2;
            $receivesInfo->read_time = date("Y-m-d H:i:s");
            $receivesInfo->save();
        }

        /** @var ApprovalLogRepository $approvalLogRepository */
        $approvalLogRepository = app()->make(ApprovalLogRepository::class);
        $logData['user_id'] = $this->request->userId;
        $logData['flow_id'] = $receivesInfo['flow_id'];
        $logData['remark'] = '查阅内容';
        $approvalLogRepository->addInfo($logData, $this->request->propertyId, $this->request->userId);


        if ($receivesInfo['flow_type'] == 'expend_apply') {
            ## 报销流程
            /** @var WorkExpendApplyRepository $workExpendApplyRepository */
            $workExpendApplyRepository = app()->make(WorkExpendApplyRepository::class);
            $info = $workExpendApplyRepository->get($receivesInfo['source_id']);
            $info['flow_id'] = $receivesInfo['flow_id'];
            return $this->fetch('work/expend/detail', [
                'info' => $info
            ]);
        }
        if ($receivesInfo['flow_type'] == 'for_leave') {
            ## 请假流程

        }

    }

    /**
     * 审批
     * @return void
     *
     * @author Amos
     * 2024-05-24 16:29
     */
    public function approvalSubmit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'receives_id' => '',
                'status' => '',
                'remark' => ''
            ]);
            $receivesInfo = $this->repository->get($param['receives_id']);
            if (!$receivesInfo) {
                return $this->error('参数错误');
            }
            if ($receivesInfo['status'] != 1 && $receivesInfo['status'] != 3) {
                return $this->error('非法操作');
            }
            if ($receivesInfo['present_uid'] != $this->request->userId) {
                return $this->error('非法操作');
            }
            validate(ApprovalReceivesValidate::class)->scene('approvalSubmit')->check($param);
            try {
                $res = $this->repository->approvalSubmitInfo($receivesInfo,$param,$this->request->userId);
                if ($res) {
                    return $this->success('批复成功');
                } else {
                    return $this->error('批复失败');
                }
            } catch (\Exception $e) {
                exception_log('流程审批失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $receivesId = (int)$this->request->param('receives_id');
            if ($receivesId <= 0) {
                return $this->error('参数错误');
            }
            $receivesInfo = $this->repository->get($receivesId);
            if (!$receivesInfo) {
                return $this->error('信息不存在');
            }
            if ($receivesInfo['present_uid'] != $this->request->userId) {
                return $this->error('非法操作');
            }
            ## 调整阅读
            if ($receivesInfo['is_check'] == 1) {
                $receivesInfo->is_check = 2;
                $receivesInfo->read_time = date("Y-m-d H:i:s");
                $receivesInfo->save();
            }

            /** @var ApprovalLogRepository $approvalLogRepository */
            $approvalLogRepository = app()->make(ApprovalLogRepository::class);
            $logData['user_id'] = $this->request->userId;
            $logData['flow_id'] = $receivesInfo['flow_id'];
            $logData['remark'] = '查阅内容';
            $approvalLogRepository->addInfo($logData, $this->request->propertyId, $this->request->userId);

            if ($receivesInfo['flow_type'] == 'expend_apply') {
                ## 报销流程
                /** @var WorkExpendApplyRepository $workExpendApplyRepository */
                $workExpendApplyRepository = app()->make(WorkExpendApplyRepository::class);
                $info = $workExpendApplyRepository->get($receivesInfo['source_id']);
                $info['flow_id'] = $receivesInfo['flow_id'];
                $info['receives_id'] = $receivesId;
                return $this->fetch('work/expend/approval', [
                    'info' => $info,
                    'receivesStatus' => $receivesInfo['status'],
                ]);
            }

            if ($receivesInfo['flow_type'] == 'for_leave') {
                ## 请假流程

            }
        }


    }


}